package cn.wolfcode.cms.service.impl;

import cn.wolfcode.cms.domain.Employee;
import cn.wolfcode.cms.domain.Role;
import cn.wolfcode.cms.mapper.EmployeeMapper;
import cn.wolfcode.cms.query.EmployeeQueryObject;
import cn.wolfcode.cms.service.IEmployeeService;
import cn.wolfcode.cms.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    public void save(Employee entity) {
        //添加默认数据
        entity.setPassword("1"); //默认密码,shiro后在加密
        entity.setInputtime(new Date()); //入职时间
        entity.setState(Employee.STATE_NORMAL); //员工状态
        entity.setAdmin(false); //是否超管
        employeeMapper.insert(entity);

        //维护与角色的关系
        List<Role> roles = entity.getRoles();
        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                employeeMapper.insertRelation(entity.getId(), role.getId());
            }
        }


    }

    public void update(Employee entity) {
        //打破关系
        employeeMapper.deleteRelation(entity.getId());
        employeeMapper.updateByPrimaryKey(entity);
        //维护与角色的关系
        List<Role> roles = entity.getRoles();
        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                employeeMapper.insertRelation(entity.getId(), role.getId());
            }
        }
    }

    public void delete(Long id) {
        //打破关系
        employeeMapper.deleteRelation(id);

        employeeMapper.deleteByPrimaryKey(id);
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public List<Employee> list() {
        return employeeMapper.selectAll();
    }


    public PageResult query(EmployeeQueryObject qo) {
        //查总数
        int total = employeeMapper.queryForCount(qo);
        if(total == 0){
            return new PageResult();
        }
        //查数据
        List<Employee> rows = employeeMapper.queryForList(qo);
        return new PageResult(total, rows);
    }

    public void quit(Long id) {
        employeeMapper.changeState(id);
    }

    public Employee getEmployeeByName(String username) {

        return employeeMapper.getEmployeeByName(username);
    }
}
